<template>
  <div class="app-container">
    <!-- 添加物资按钮 -->
    <el-button type="success" @click="showDrawer(false)" style="margin-bottom: 20px;">
      <i class="el-icon-plus"></i> 新增资源
    </el-button>

   <!-- 物资列表表格 -->
    <!-- 物资列表表格 -->
  <el-table :data="supplies" style="width: 100%" border>
    <el-table-column prop="name" label="物资名称" width="180"></el-table-column>
    <el-table-column prop="category" label="类别" width="180"></el-table-column>
    <el-table-column label="资源类型">
      <template slot-scope="scope">
        <!-- 根据 type 的值显示不同的文本 -->
        <span v-if="scope.row.type === 'tool'">工具类</span>
        <span v-else-if="scope.row.type === 'consumable'">可消耗品</span>
        <span v-else>{{ scope.row.type }}其他</span> <!-- 如果有其他类型的处理 -->
      </template>
    </el-table-column>
    <el-table-column prop="unit" label="单位"></el-table-column>
    <el-table-column prop="currentQuantity" label="库存数量"></el-table-column>
    <el-table-column prop="description" label="描述"></el-table-column>
    <el-table-column label="操作" width="300"> <!-- 设置操作列的宽度 -->
      <template slot-scope="scope">
        <div class="button-group">
          <el-button @click="showDrawer(true, scope.row)" type="primary" size="mini">编辑</el-button>
          <el-button type="danger" size="mini" @click="handleDeleteConfirm(scope.row.id)">删除</el-button>
          <el-button v-if="scope.row.type === 'tool'" type="warning" size="mini" @click="showAddMaintenanceDialog(scope.row)">维护</el-button>
          <el-button v-if="scope.row.type === 'tool'" type="info" size="mini"
            @click="viewMaintenance(scope.row.id)">维护记录</el-button>
        </div>
      </template>
    </el-table-column>
  </el-table>

    <!-- 抽屉式组件 - 编辑/新增物资 -->
    <el-drawer :title="drawerTitle" :visible.sync="drawerVisible" direction="rtl" size="40%" :before-close="handleClose">
      <el-form :model="form" label-width="100px" :rules="rules" ref="formRef">
        <el-form-item label="物资名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入物资名称"></el-input>
        </el-form-item>
        <el-form-item label="类别" prop="category">
          <el-select v-model="form.category" placeholder="请选择类别">
            <el-option label="农药" value="农药"></el-option>
            <el-option label="化肥" value="化肥"></el-option>
            <el-option label="工具" value="工具"></el-option>
            <el-option label="其他" value="其他"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="资源类型" prop="type">
          <el-select v-model="form.type" placeholder="请选择资源类型">
            <el-option label="可消耗品" value="consumable"></el-option>
            <el-option label="工具" value="tool"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="单位" prop="unit">
          <el-input v-model="form.unit" placeholder="请输入单位"></el-input>
        </el-form-item>
        <!-- <el-form-item label="库存数量" prop="currentQuantity">
          <el-input-number v-model="form.currentQuantity" controls-position="right" :min="0"></el-input-number>
        </el-form-item> -->
        <el-form-item label="是否需要维护" v-if="form.type === 'tool'">
          <el-switch v-model="form.isMaintainable"></el-switch>
        </el-form-item>
        <el-form-item label="下次维护日期" v-if="form.isMaintainable">
          <el-date-picker v-model="form.nextMaintenanceDate" type="date" placeholder="选择日期"></el-date-picker>
        </el-form-item>
        <el-form-item label="描述" prop="description">
            <el-input type="textarea" v-model="form.description" placeholder="请输入描述"></el-input>
          </el-form-item>
      </el-form>
      <div class="drawer-footer">
        <el-button @click="drawerVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitForm('formRef')">确 定</el-button>
      </div>
    </el-drawer>

    <!-- 查看维护记录对话框 -->
   <el-dialog title="维护记录" :visible.sync="maintenanceDialogVisible" width="40%">
        <el-table :data="maintenanceRecords" style="width: 100%">
          <el-table-column prop="maintenanceDate" label="维护日期"></el-table-column>
          <el-table-column prop="performedBy" label="执行人"></el-table-column>
          <el-table-column prop="remarks" label="备注"></el-table-column>
        </el-table>
        <span slot="footer" class="dialog-footer">
          <el-button @click="maintenanceDialogVisible = false">关 闭</el-button>
        </span>
      </el-dialog>

      <!-- 新增维护信息对话框 -->
 <el-dialog title="添加维护信息" :visible.sync="addMaintenanceDialogVisible" width="40%">
      <el-form :model="maintenanceForm" label-width="120px" :rules="maintenanceRules" ref="maintenanceFormRef">
        <el-form-item label="物资ID" prop="materialId">
          <el-input v-model="maintenanceForm.materialId" disabled></el-input>
        </el-form-item>
        <el-form-item label="物资名称" prop="materialName">
          <el-input v-model="maintenanceForm.materialName" disabled></el-input>
        </el-form-item>
        <el-form-item label="维护数量" prop="quantity">
          <el-input-number v-model="maintenanceForm.quantity" controls-position="right" :min="1"></el-input-number>
        </el-form-item>
        <el-form-item label="维护日期" prop="maintenanceDate">
          <el-date-picker v-model="maintenanceForm.maintenanceDate" type="date" placeholder="选择日期"></el-date-picker>
        </el-form-item>
        <el-form-item label="维护类型" prop="maintenanceType">
          <el-select v-model="maintenanceForm.maintenanceType" placeholder="请选择维护类型">
            <el-option label="常规检查" value="常规检查"></el-option>
            <el-option label="紧急维修" value="紧急维修"></el-option>
            <!-- 可以添加更多选项 -->
          </el-select>
        </el-form-item>
        <el-form-item label="维护状态" prop="status">
          <el-select v-model="maintenanceForm.status" placeholder="请选择状态">
            <!-- <el-option label="已安排" value="scheduled"></el-option> -->
            <el-option label="进行中" value="进行中"></el-option>
            <!-- <el-option label="已完成" value="completed"></el-option> -->
          </el-select>
        </el-form-item>
        <el-form-item label="备注" prop="remarks">
          <el-input type="textarea" v-model="maintenanceForm.remarks" placeholder="请输入备注"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addMaintenanceDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitMaintenance('maintenanceFormRef')">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { mapState, mapActions } from 'vuex';
export default {
  data() {
    return {
      drawerVisible: false,
      maintenanceDialogVisible: false,
      drawerTitle: '',
      form: {
        id: null,
        name: '',
        category: '',
        type: '',
        unit: '',
        currentQuantity: null,
        isMaintainable: false,
        nextMaintenanceDate: null,
        description: '' // 新增字段
      },
      rules: {
        name: [{ required: true, message: '请输入物资名称', trigger: 'blur' }],
        category: [{ required: true, message: '请选择类别', trigger: 'change' }],
        type: [{ required: true, message: '请选择资源类型', trigger: 'change' }],
        unit: [{ required: true, message: '请输入单位', trigger: 'blur' }],
        current_quantity: [{ required: true, message: '请输入库存数量', trigger: 'blur' }],
        description: [{ required: false, message: '请输入描述', trigger: 'blur' }] // 新增规则
      },
      addMaintenanceDialogVisible: false,
     maintenanceForm: {
        materialId: '', // 假设由父组件传递或通过其他方式获取
        materialName: '', // 同上
        quantity: 1, // 默认值为1
        maintenanceDate: '',
        maintenanceType: '',
        status: '',
        remarks: ''
      },
      maintenanceRules: {
        quantity: [{ required: true, message: '请输入维护数量', trigger: 'blur' }],
        maintenanceDate: [{ required: true, message: '请选择维护日期', trigger: 'change' }],
        performedBy: [{ required: true, message: '请输入执行人', trigger: 'blur' }]
      }
      // maintenanceRecords: [],
      // 用于存储物资条目的状态变量
      // supplies: [] 
    };
  },
  computed: {
    ...mapState('supplies', ['supplies', 'loading', 'error']),
    ...mapState('maintenance', ['loading', 'error', 'maintenanceRecords'])
  },
  methods: {
    ...mapActions('supplies', ['fetchSupplies', 'createSupply', 'updateSupply', 'deleteSupply']),
    ...mapActions('maintenance', ['fetchMaintenanceRecords', 'createMaintenance']),
  
    showDrawer(isEdit, row = null) {
      if (isEdit && row) {
        this.drawerTitle = '编辑物资信息';
        this.form = { ...row }; // 深拷贝避免直接修改原始数据
      } else {
        this.drawerTitle = '新增资源';
        this.form = {}; // 清空表单
      }
      this.drawerVisible = true;
    },
    handleDeleteConfirm(id) {
      this.$confirm('确定要删除此物资信息和其对应的维修记录吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.deleteSupply(id).then(() => {
          this.$message({
            type: 'success',
            message: '删除成功!'
          });
        });
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },
    handleClose(done) {
      this.$confirm('确认关闭？')
        .then(_ => {
          done();
        })
        .catch(_ => { });
    },
    async submitForm(formName) {
      this.$refs[formName].validate(async (valid) => {
        if (valid) {
          try {
            let action = this.form.id ? 'updateSupply' : 'createSupply';
            await this[action]({ id: this.form.id, data: this.form });
            console.log(this.form)
            this.$message({
              type: 'success',
              message: `${this.form.id ? '更新' : '创建'}成功!`
            });

            this.drawerVisible = false;

            // 重置表单（如果需要）
            this.form = {};
          } catch (error) {
            console.error('提交失败:', error);
            this.$message({
              type: 'error',
              message: '提交失败，请检查控制台日志'
            });
          }
        } else {
          console.log('表单验证失败');
          return false;
        }
      });
    },
    viewMaintenance(materialId) {
      this.fetchMaintenanceRecords(materialId)
        .then(() => {
          this.maintenanceDialogVisible = true;
        })
        .catch(error => {
          console.error('Failed to fetch maintenance records:', error);
        });
    },
    // ... 其他方法 ...
    showAddMaintenanceDialog(row) {
      this.maintenanceForm.materialId = row.id;
      this.maintenanceForm.materialName = row.name;
      this.addMaintenanceDialogVisible = true;
    },
    async submitMaintenance(formName) {
      this.$refs[formName].validate(async (valid) => {
        if (valid) {
          try {
            await this.createMaintenance(this.maintenanceForm);
            
            this.$message({
              type: 'success',
              message: '维护信息添加成功!'
            });
            this.addMaintenanceDialogVisible = false;
            this.maintenanceForm = {}; // 清空表单
            this.fetchSupplies();
          } catch (error) {
            console.error('提交失败:', error);
            this.$message({
              type: 'error',
              message: '提交失败，请检查控制台日志'
            });
          }
        } else {
          console.log('表单验证失败');
          return false;
        }
      });
    }
  
  },
  created() {
    this.fetchSupplies();
    // 在组件创建时初始化静态数据
    // this.initSupplies();
  }
};
</script>


<style scoped>
.app-container {
  padding: 20px;
  background-color: #f0f2f5;
}

.el-table {
  margin-top: 0px;
}


.el-button+.el-button {
    margin-left: 3px;
}
/* 操作按钮组样式 */
.button-group {
  display: flex;
  justify-content: space-between;
  /* 均匀分布按钮 */
  flex-wrap: nowrap;
  /* 防止换行 */
  width: 100%;
  /* 确保按钮组占据整个操作列的宽度 */
  align-items: center;
  /* 垂直居中对齐 */
}

.button-group .el-button {
  flex: 1 1 auto;
  /* 每个按钮根据剩余空间自动增长，但允许收缩 */
  margin-right: 0px;
  /* 减小按钮间有间隔 */
  padding: 8px 10px;
  /* 减少内边距以适应更小的空间 */
  min-width: 45px;
  /* 减少最小宽度 */
  max-width: calc(25% - 8px);
  /* 考虑到间距后计算最大宽度 */
  text-align: center;
  /* 居中按钮文本 */
  box-sizing: border-box;
  /* 确保内边距和边框被包含在元素的总宽度和高度之内 */
  white-space: nowrap;
  /* 防止按钮文本换行 */
  overflow: hidden;
  /* 隐藏超出的内容 */
  /* text-overflow: ellipsis; */
  /* 显示省略号 */
}

.button-group .el-button:last-child {
  margin-right: 0;
  /* 最后一个按钮不需要右边距 */
}

/* 当按钮数量少于4个时，使用空的 div 占位符以保持布局整齐 */
.button-group::after {
  content: '';
  flex: 1 1 auto;
  /* 创建一个灵活的占位符 */
  width: 0;
  /* 不占用额外宽度 */
}

/* 自定义抽屉底部样式 */
.drawer-footer {
  text-align: right;
  padding: 10px 20px 20px;
  border-top: 1px solid #dcdfe6;
}

/* 自定义表格样式 */
.el-table th {
  background-color: #f5f7fa;
  color: #909399;
  font-weight: bold;
}

.el-table td {
  padding: 12px 0;
}

/* 自定义弹出框样式 */
.el-dialog__header {
  background-color: #ecf5ff;
  padding: 15px;
  border-bottom: 1px solid #ebeef5;
}

.el-dialog__body {
  padding: 20px;
}

.el-dialog__footer {
  padding: 10px 20px 20px;
  text-align: right;
  border-top: 1px solid #ebeef5;
}</style>